/*******************************************************************************
 * Copyright 2013 Gabriele Mariotti
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *******************************************************************************/
package com.corex.navigationdrawer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.corex.staticclasses.PrivateData;
import com.corex.staticclasses.StaticData;
import com.corex.utils.Constants;
import com.corex.vinayak.R;
import com.corex.vinayak.TimeTableDetailsActivity;
import com.corex.vinayak.views.LoginScreen;
import com.corex.vinayak.views.LoginSuccessFragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.CalendarView.OnDateChangeListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class LoginSuccessActivity extends Activity {
	private TextView welcomeUser;
	private ListView mDrawerList;
	LinearLayout leftMenu;
	private View calendar;
	private DrawerLayout mDrawer;
	private CustomActionBarDrawerToggle mDrawerToggle;
	private Button button_exit;
    private Button button_logout;


	private String[] menuItems;
	private String[] classListArr;

	@Override
	public void onBackPressed() {
		
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_drawer);

		if (savedInstanceState == null) {
			getFragmentManager()
					.beginTransaction()
					.add(R.id.loginsuccesscontainer, new LoginSuccessFragment())
					.commit();
		}
		// enable ActionBar app icon to behave as action to toggle nav drawer
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setHomeButtonEnabled(true);

		mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		welcomeUser = (TextView) findViewById(R.id.welcome_user);
		button_exit = (Button) findViewById(R.id.button_exit);
        button_logout = (Button) findViewById(R.id.button_logout);
		mDrawer.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

		_initMenu();
		mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawer);
		mDrawer.setDrawerListener(mDrawerToggle);
		button_exit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(LoginSuccessActivity.this)
						.setIcon(android.R.drawable.ic_dialog_alert)
						.setIcon(android.R.drawable.ic_dialog_alert)
						.setTitle(R.string.title_exit)
						.setMessage(R.string.exit_app_msg)
						.setPositiveButton(R.string.yes,
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										LoginSuccessActivity.this.finish();
									}
								}).setNegativeButton(R.string.no, null).show();
			}
		});

        button_logout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(LoginSuccessActivity.this)
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle(R.string.title_logout)
                        .setMessage(R.string.logout_app_msg)
                        .setPositiveButton(R.string.yes,
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        PrivateData privateData = new PrivateData(getApplicationContext());
                                        privateData.cleanPreference();
                                        LoginSuccessActivity.this.finish();
                                    }
                                }).setNegativeButton(R.string.no, null).show();
            }
        });

	}

	private void _initMenu() {
		calendar = findViewById(R.id.drawer_calendar);
		NsMenuAdapter mAdapter = new NsMenuAdapter(this);

		welcomeUser.setText("Welcome "
				+ StaticData.loginResponse.getUserBean().getFirstname());

		List classLists = StaticData.loginResponse.getStudentScheduleData()
				.get(Constants.CLASS_LIST);
		classListArr = new String[classLists.size()];
		List clslist = StaticData.loginResponse.getStudentScheduleData().get(
				Constants.CLASS_LIST);

		for (int i = 0; i < clslist.size(); i++) {
			List clslistInner = (List) clslist.get(i);
			String className = (String) clslistInner.get(0);
			if (className.trim().length() == 0)
				className = "[Not Mentioned]";

			classListArr[i] = className;
		}

		String[] menuItemsIcon = getResources().getStringArray(
				R.array.ns_menu_items_icon);

		int res = 0;

		for (String item : classListArr) {

			String id_title = item;
			int id_icon = getResources().getIdentifier(menuItemsIcon[res],
					"drawable", this.getPackageName());

			NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
			/*
            if (res == 1)
				mItem.counter = 12; // it is just an example...
			if (res == 3)
				mItem.counter = 3; // it is just an example...
			*/
			mAdapter.addItem(mItem);
			res++;
		}

		mDrawerList = (ListView) findViewById(R.id.drawer_classList);
		leftMenu = (LinearLayout) findViewById(R.id.drawer_classList_Menu);
		if (mDrawerList != null)
			mDrawerList.setAdapter(mAdapter);

		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		((CalendarView) calendar)
				.setOnDateChangeListener(new OnDateChangeListener() {

					@Override
					public void onSelectedDayChange(CalendarView view,
							int year, int month, int dayOfMonth) {
						mDrawer.closeDrawer(Gravity.RIGHT);
					}
				});

	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.timetable_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* Called whenever we call invalidateOptionsMenu() */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// If the nav drawer is open, hide action items related to the content
		// view
		// boolean drawerOpen = mDrawer.isDrawerOpen(mDrawerList);
		boolean drawerOpen = mDrawer.isDrawerOpen(leftMenu);
		// menu.findItem(R.id.action_save).setVisible(!drawerOpen);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		/*
		 * The action bar home/up should open or close the drawer.
		 * ActionBarDrawerToggle will take care of this.
		 */
		if ("calendar".equals(item.getTitle())) {
			boolean isCalenderDrawerOpned = mDrawer.isDrawerOpen(calendar);
			if (!isCalenderDrawerOpned) {
				mDrawer.openDrawer(Gravity.RIGHT);
				mDrawer.closeDrawer(Gravity.LEFT);
			} else {
				mDrawer.closeDrawer(Gravity.RIGHT);
			}
			return true;
		} else {
			// boolean isListDrawerOpned = mDrawer.isDrawerOpen(mDrawerList);
			boolean isListDrawerOpned = mDrawer.isDrawerOpen(leftMenu);
			if (!isListDrawerOpned) {
				mDrawer.openDrawer(Gravity.LEFT);
				mDrawer.closeDrawer(Gravity.RIGHT);
			} else {
				mDrawer.closeDrawer(Gravity.LEFT);
			}
			return true;
		}
	}

	private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {

		public CustomActionBarDrawerToggle(Activity mActivity,
				DrawerLayout mDrawerLayout) {
			super(mActivity, mDrawerLayout, R.drawable.ic_drawer,
					R.string.ns_menu_open, R.string.ns_menu_close);
		}

		@Override
		public void onDrawerClosed(View view) {
			getActionBar().setTitle(getString(R.string.ns_menu_close));
			invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
		}

		@Override
		public void onDrawerOpened(View drawerView) {
			if (drawerView.getId() == R.id.drawer_calendar) {
				getActionBar().setTitle(
						getString(R.string.calendar_drawer_open));
                loadTimeTable();
			} else if (drawerView.getId() == R.id.drawer_classList) {
				getActionBar().setTitle(
						getString(R.string.classlist_drawer_open));
			}
			invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
		}
	}

	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// Highlight the selected item, update the title, and close the
			// drawer
			// update selected item and title, then close the drawer
			mDrawerList.setItemChecked(position, true);
			String text = "menu click... should be implemented";
			Toast.makeText(LoginSuccessActivity.this, text, Toast.LENGTH_LONG)
					.show();
			// You should reset item counter
			// mDrawer.closeDrawer(mDrawerList);
			mDrawer.closeDrawer(leftMenu);

		}

	}

    private void loadTimeTable(){
        Bundle bundle = new Bundle();
        final TimeTableDetailsActivity timeTableDetailsFragment = new TimeTableDetailsActivity();
        final FragmentManager fragmentManager = getFragmentManager();
        //Toast.makeText(rootView.getContext(),"Fetching...", Toast.LENGTH_SHORT).show();
        Date dateUtil = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String date = simpleDateFormat.format(dateUtil);
        bundle.putString(Constants.TIMETABLE_SELECTED_DATE, date);
        // set Fragmentclass Arguments
        Bundle bundleOther = timeTableDetailsFragment.getArguments();
        if(bundleOther==null){
            timeTableDetailsFragment.setArguments(bundle);
        }else{
            timeTableDetailsFragment.getArguments().putString(Constants.TIMETABLE_SELECTED_DATE, date);
        }

        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.loginsuccesscontainer, timeTableDetailsFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}
